import tkinter

# 报文转化
class MessageInvert():
    def __init__(self,tk_mainwindow) -> None:
        self.tk_mainwindow = tk_mainwindow
        self.text_list = []
        self.horizontal = 1366
        self.vertical = 720
        self.tk_mainwindow.grid_columnconfigure(0,weight=1)
        self.tk_mainwindow.grid_columnconfigure(1,weight=1)
        self.showWidget()
        

    def showWidget(self):
        self.tk_mainwindow.geometry(f'{self.horizontal}x{self.vertical}')
        # self.destory_widget_all()
        lable_1 = tkinter.Label(self.tk_mainwindow, text="原报文")
        lable_1.grid(row=0, column=0)
        lable_2 =  tkinter.Label(self.tk_mainwindow, text="字段列表")
        lable_2.grid(row=0, column=1,padx=(10,10))

        text_1 = tkinter.Text(self.tk_mainwindow,width=50, height=40)
        text_1.grid(row=1,column=0,sticky='WENS')

        text_2 = tkinter.Text(self.tk_mainwindow,width=50, height=40)
        text_2.grid(row=1,column=1,padx=(10,10),sticky='WENS')

        self.text_list.append(text_1)
        self.text_list.append(text_2)

        self.button_commit = tkinter.Button(self.tk_mainwindow, text="转化", bg="lightblue", width=10,command=self.transform_data)
        self.button_commit.grid(row=10,column=0)

    def transform_data(self):
        real_data = str(self.text_list[0].get('1.0','end'))
        real_data.strip()
        self.deal_with_data(real_data)

    def deal_with_data(self,data):
        self.text_list[1].delete('1.0','end')
        key_list = []
        value_list = []

        datas = data.split('\n')
        values = ''

        # temp_list = []
        
        for i in datas:
            if '#' in i:
                key = i.split('\t')[1]
                key_list.append(key)
            else:
                # print(i)
                # temp_list.append(i)
                values = values + i.strip('\n')

        # print(temp_list)

        value_list = values.split('|')     
        value_list.pop(0) 

        # n = 0
        # for i in value_list:
        #     n += 1
        #     print(n,i)

        if len(key_list) == len(value_list) :
            l = len(key_list)
            for n in range(l):
                key_value = '"'+str(key_list[l-1-n])+'"'+':'+'"'+str(value_list[l-1-n].strip()) +'"'+ '\n'
                self.text_list[1].insert('1.0',key_value)
        else:
            error = f'数据有误，字段有{len(key_list)}个,值有{len(value_list)}个'
            self.text_list[1].insert('1.0',error)